<template>
  <div>
     <!-- <img ref="loginImg" src="@/assets/bj.png" width="100" height="100"> -->
    <canvas ref="myCanvas" width="500" height="500"  style="border:1px solid #d3d3d3;"></canvas>
  </div>

</template>

<script>
export default {
  name: 'Canvas',
  components: {
  
  },
  data(){
    return {
      
    }
  },
  methods:{
    
  },
  created(){

  },
  mounted(){
    // var c=document.getElementById("myCanvas");
    //获取画布Dom对象
    var c=this.$refs.myCanvas
    //获取画布
    var ctx=c.getContext("2d");
    // let img = this.$refs.loginImg
    let css1 = {
      x:0,
      y:0,
      w:100,
      h:100,
      dx:0,
      dy:0,
      speed:10
    }
    //边缘检测
    function detectBorder(){
      if(css1.x + css1.w > c.width)  css1.x = c.width -css1.w
      if(css1.x < 0) css1.x = 0
      if(css1.y + css1.h > c.height) css1.y = c.height - css1.h
      if(css1.y<0)  css1.y = 0
    }
    //方向键控制
    function moveRight(){
      console.log('moveRight')
      css1.dx = css1.speed;
      css1.x += css1.dx;
      //清除画布的宽高
      ctx.clearRect(0,0,c.width,c.height)
      ctx.drawImage(img,css1.x,css1.y,css1.w,css1.h)
      detectBorder()
    }
    function moveLeft(){
      console.log('moveLeft')
      css1.dx  = css1.speed*-1;
      // css1.dx  = css1.dx -5;
      css1.x += css1.dx
      ctx.clearRect(0,0,c.width,c.height)
      ctx.drawImage(img,css1.x,css1.y,css1.w,css1.h)
      detectBorder()

    }
    function moveUp(){
      console.log('moveUp')
      css1.dy  = css1.speed*-1;
      css1.y += css1.dy
      ctx.clearRect(0,0,c.width,c.height)
      ctx.drawImage(img,css1.x,css1.y,css1.w,css1.h)
      detectBorder()
    }
    function moveDown(){
      console.log('moveDown')
      css1.dy  = css1.speed;
      css1.y += css1.dy
      ctx.clearRect(0,0,c.width,c.height)
      ctx.drawImage(img,css1.x,css1.y,css1.w,css1.h)
      detectBorder()
    }

    function keydown(e){
      console.log('keydown',e)
      switch(e.key){
        case 'ArrowRight':
          moveRight();
          break;
        case 'ArrowLeft':
          moveLeft();
          break;
        case 'ArrowUp':
          moveUp();
          break;
        case 'ArrowDown':
          moveDown();
          break;
      }
    }

    function keyup(e){
      console.log('keyup',e)
    }

    document.addEventListener('keydown',keydown)
    document.addEventListener('keyup',keyup)


    let img = new Image()
    img.onload = function(){
      ctx.drawImage(img,css1.x,css1.y,css1.w,css1.h)
    }
    //调用本地图
    //img.src = require('@/assets/bj.png')
    ///网络图
    img.src='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1113%2F052420110515%2F200524110515-2-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653481070&t=c994d5691789a339761258ddd2885072'

  }
}
</script>

<style>

</style>